package com.clusterswisdom.horn.api.tmall.action.alipay;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.taobao.api.domain.AlipayRecord;
import com.taobao.api.response.AlipayUserAccountreportGetResponse;

public class UserTradeSearchAction extends AbstractTmallAction implements
		HornAction {

	@Override
	public HornResponse execute(ApiConfig config, JSONObject param)
			throws Exception {
		Date start_time = param.getDate("start_time");
		Date end_time = param.getDate("end_time");
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(start_time);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end_time);
		List<AlipayRecord> alipayRecords = new LinkedList<AlipayRecord>();
		while (startTime.getTimeInMillis() <= endTime.getTimeInMillis()) {
			alipayRecords.addAll(getAlipayRecord(startTime));
		}
		return new HornResponse(true, alipayRecords);
	}
	public List<AlipayRecord> getAlipayRecord(Calendar startTime) throws Exception {
		JSONObject param = new JSONObject();
		param.put("start_time", startTime.getTime());
		
		List<AlipayRecord> alipayRecords = new LinkedList<AlipayRecord>();
		startTime.add(Calendar.DAY_OF_YEAR, 1);
		param.put("end_time", startTime.getTime());
		
		int page = 1;
		boolean isNotEnd = true;
		do {
			param.put("page_no", page);
			AlipayUserAccountreportGetResponse response = (AlipayUserAccountreportGetResponse) TmallInstance.getInstance().executeRequest(param, "alipay", "alipayRecord");
			//log.debug("get page AlipayUserAccountreport : " + DateFormatUtils.format(startTime, "yyyy-MM-dd") + ";" + page + "; datas " + response.isSuccess() + ";" + response.getAlipayRecords());
			if (response.isSuccess() && response.getAlipayRecords() != null) {
				alipayRecords.addAll(response.getAlipayRecords());
			}
			
			Long totalPages = response.getTotalPages();
			if (totalPages == null) {
				totalPages = 1l;
			}
			
			isNotEnd = page < totalPages;
			page++;

		} while (isNotEnd);
		return alipayRecords;
	}
}
